<template>
  <div class="printer-container">
    <el-card shadow="never">
      <template #header>
        <div class="clearfix">
          <span>打印机配置</span>
          <el-button style="float: right" type="primary" :icon="Plus" @click="openAdd">新增</el-button>
        </div>
      </template>

      <!-- 列表 -->
      <el-table v-loading="loading" :data="list" row-key="id" size="small">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="ip" label="IP" />
        <el-table-column prop="port" label="端口" width="80" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{row}">
            <el-tag :type="row.type==='KITCHEN'?'warning':'info'">
              {{ row.type==='KITCHEN'?'后厨':'前台' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="启用" width="80">
          <template #default="{row}">
            <el-switch v-model="row.enabled" @change="toggleEnable(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{row}">
            <el-button size="small" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="del(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="show" :title="isAdd?'新增打印机':'编辑打印机'" width="420px" @closed="reset">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属门店" prop="storeId">
          <el-select v-model="form.storeId" clearable placeholder="全部门店/管理员可见">
            <el-option v-for="s in stores" :key="s.id" :label="s.storeName" :value="s.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="如：后厨热敏" />
        </el-form-item>
        <el-form-item label="IP" prop="ip">
          <el-input v-model="form.ip" placeholder="192.168.1.200" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input-number v-model="form.port" :min="1" :max="65535" controls-position="right" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="KITCHEN">后厨</el-radio>
            <el-radio label="FRONT">前台</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="form.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show=false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { http } from '@/api/request'

interface Printer {
  id?: number
  storeId: number | null
  name: string
  ip: string
  port: number
  type: 'KITCHEN'|'FRONT'
  enabled: boolean
}
interface Store { id: number; storeName: string }

const loading = ref(false)
const list = ref<Printer[]>([])
const stores = ref<Store[]>([])

const show = ref(false)
const isAdd = ref(true)
const saveLoading = ref(false)
const formRef = ref()
const form = reactive<Printer>({
  storeId: null,
  name: '',
  ip: '',
  port: 9100,
  type: 'KITCHEN',
  enabled: true
})
const rules = {
  storeId: [{ required: true, message: '请选择门店', trigger: 'change' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  ip: [{ required: true, message: '请输入IP', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

function loadList() {
  loading.value = true
  http.get('/admin/printers').then((res: any) => {
    list.value = res.data
  }).finally(() => loading.value = false)
}
function loadStores() {
  http.get('/admin/stores/page', { params: { size: 999 } }).then((res: any) => {
    stores.value = res.data.records
  })
}
function openAdd() {
  isAdd.value = true
  show.value = true
}
function openEdit(row: Printer) {
  isAdd.value = false
  Object.assign(form, row)
  show.value = true
}
function toggleEnable(row: Printer) {
  http.put(`/admin/printers/${row.id}`, row).catch(() => row.enabled = !row.enabled)
}
function submit() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return
    saveLoading.value = true
    const req = isAdd.value
      ? http.post('/admin/printers', form)
      : http.put(`/admin/printers/${form.id}`, form)
    req.then(() => {
      ElMessage.success('保存成功')
      show.value = false
      loadList()
    }).finally(() => saveLoading.value = false)
  })
}
function del(row: Printer) {
  ElMessageBox.confirm(`确定删除打印机【${row.name}】？`, '提示', { type: 'warning' })
    .then(() => http.delete(`/admin/printers/${row.id}`))
    .then(() => {
      ElMessage.success('删除成功')
      loadList()
    })
}
function reset() {
  formRef.value.resetFields()
  Object.assign(form, {
    storeId: null,
    name: '',
    ip: '',
    port: 9100,
    type: 'KITCHEN',
    enabled: true
  })
}

onMounted(() => {
  loadList()
  loadStores()
})
</script>

<style scoped>
.printer-container .el-card { margin: 16px; }
</style>